package logics

import (
	"encoding/json"
	_const "git.900sui.cn/kc/apiPay/lang/const"
	"git.900sui.cn/kc/base/common/functions"
	"git.900sui.cn/kc/base/utils"
	pay2 "git.900sui.cn/kc/rpcinterface/client/pay"
	"git.900sui.cn/kc/rpcinterface/interface/pay"
	"log"
)

//银联支付类型
type YinlianPayLogic struct{}

func (this *YinlianPayLogic) Do(t functions.Controller, orderSnField string, cidField string) {
	order_sn := t.Ctx.GetString(orderSnField)
	cid := t.Ctx.GetString(cidField)
	log.Printf("cid: %s", cid)
	userAuthCode := t.Input.Post("userAuthCode").String()
	if len(userAuthCode) == 0 {
		t.Output.Error(_const.UserAuthCodeIsEmpty)
		return
	}
	respCode := t.Input.Post("respCode").String()
	if len(respCode) == 0 {
		t.Output.Error(_const.RespCodeIsEmpty)
		return
	}
	if respCode != "00" && respCode != "34" {
		t.Output.Error(_const.RespCodeIsError)
		return
	}
	userAgent := t.Input.Post("userAgent").String()
	if len(userAgent) == 0 {
		t.Output.Error(_const.UserAgentIsEmpty)
		return
	}
	utils.Logerr.Printf("获取到的userAuthCode : %s  userAgent: %s responseCode: %s", userAuthCode, userAgent, respCode)

	//获取企业标识
	xindaluPayService := new(pay2.XindaluPay).Init()
	//获取银联用户标识
	args := &pay.ArgsGetPaypalTag{
		PayCode:  userAgent,
		AuthCode: userAuthCode,
		Cid:      cid,
		Ip:       functions.ClientIP(t.Ctx.Request),
	}
	reply := &pay.ReplyGetPaypalTag{}
	err := xindaluPayService.GetPaypalTag(t.Ctx.Request.Context(), args, reply)
	if err != nil {
		t.Output.Error(_const.GetPaypalTagErr)
		return
	}

	unionOrderYinlianArgs := &pay.ArgsunionidOrder{
		OrderNO:   order_sn,
		PayWay:    pay.PayWayYinlian,
		Openid:    reply.Data.UserId, //返回的用户的标识信息
		AtqTag:    reply.Data.AtqTag,
		Ip:        functions.ClientIP(t.Ctx.Request),
		CustLogin: "", //用户的手机号
		Cid:       cid,
	}
	unionOrderReply := &pay.ReplyUniondOrder{}

	err = xindaluPayService.UnionidOrder(t.Ctx.Request.Context(), unionOrderYinlianArgs, unionOrderReply)

	if err != nil {
		t.Output.Error(_const.RpcServerIsError)
		return
	}
	utils.Logerr.Printf("获取的数据: %#v", unionOrderReply)
	jsonByte, _ := json.Marshal(unionOrderReply.Data)
	log.Printf("json: %s", string(jsonByte))
	t.Output.Success(unionOrderReply.Data)
}
